package ru.avn.devtool4j.spi.writers.impl;

import java.lang.reflect.Modifier;
import java.util.Arrays;

import ru.avn.devtool4j.spi.writers.FieldWriter;

public class FieldWritterImpl implements FieldWriter {

	private String name;
	private String type;
	private int[] modifiers = new int[] {};
	private String defaultPlainText = "null";
	
	@Override
	public FieldWriter setName(String name) {
		
		if (name == null) {
			throw new IllegalArgumentException();
		}
		
		this.name = name;
		return this;
	}

	@Override
	public FieldWriter setType(Class<?> clazz) {
		if (clazz == null) {
			throw new IllegalArgumentException();
		}
		this.type = clazz.getName();
		return this;
	}

	@Override
	public FieldWriter setType(String name) {
		
		if (name == null) {
			throw new IllegalArgumentException();
		}

		try {
			Class.forName(name);
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		}
		
		
		this.type = name;
		return this;
	}

	@Override
	public FieldWriter addModifiers(int[] modifiers) {
		
		if (modifiers == null) {
			throw new IllegalArgumentException();
		}
		
		int[] newArray = new int[this.modifiers.length + modifiers.length];
		
		System.arraycopy(this.modifiers, 0, newArray, 0, this.modifiers.length);
		System.arraycopy(modifiers, 0, newArray, this.modifiers.length, modifiers.length);
		
		this.modifiers = newArray;
		
		return this;
	}

	@Override
	public FieldWriter addModifier(int modifier) {
		addModifiers(new int[] {modifier});	
		return this;
	}

	@Override
	public FieldWriter setDefault(Object object) {
		
		if (object != null) {
			
			if (!object.getClass().getName().equals(type)) {
				throw new IllegalArgumentException("Default object must have the same type as field type");
			}
			
			if (!VariableHelper.isPrimitive(object)) {
				throw new IllegalArgumentException("Unsupported type " + object.getClass());
			}
			
			defaultPlainText = VariableHelper.returnValueOfCode(object);
			
		}
				
		return this;
	}

	@Override
	public FieldWriter setDefaultPlain(String plainText) {
		
		if (plainText == null) {
			throw new IllegalArgumentException();
		}
		
		defaultPlainText = plainText;
		return this;
	}

	
	public String buildFieldCode() {
	
		StringBuilder builder = new StringBuilder();
		
		builder.append(WritterHelper.modifiers(modifiers))
		.append(" ")
		.append(type)
		.append(" ")
		.append(name)
		.append(" = ")
		.append(defaultPlainText)
		.append("");
		
		return builder.toString();
	}
	
}
